import React from 'react';
import './App.css';

import Todo from './Todo/Todo';


export default class App extends React.Component {
  constructor() {
    super();
    
    this.state = {
      list1: [],
      list2: [],
      list3: []
    }

    this.index = 0;

    window.global.addTodo = this.addTodo.bind(this);

    // load localstorage
    let local = localStorage.getItem('todolist');
    this.local = {};
    if (local) {
      this.local = JSON.parse(local);
      this.load(this.local);
    }
  }
  addTodo(todo) {
    if (this.index === 0) {
      let list1 = this.state.list1;
      list1.unshift(todo);
      this.setState({ list1 });
    } else if (this.index === 1) {
      let list2 = this.state.list2;
      list2.unshift(todo);
      this.setState({ list2 });
    } else {
      let list3 = this.state.list3;
      list3.unshift(todo);
      this.setState({ list3 });
    }
    this.index = ++this.index % 3;
    
    // save
    this.local[todo.time] = todo;
    localStorage.setItem('todolist', JSON.stringify(this.local));
  }
  commit(e) {
    let form = e.target;
    let time = new Date().getTime();
    this.addTodo({
      title: form.title.value,
      content: form.content.value,
      time,
      finished: false
    });
    e.preventDefault();
  }
  load(list) {
    let l1 = this.state.list1;
    let l2 = this.state.list2;
    let l3 = this.state.list3;

    console.log(list)

    for (let index in list) {
      let todo = list[index];
      if (this.index === 0) {
        l1.unshift(todo);
      } else if (this.index === 1) {
        l2.unshift(todo);
      } else {
        l3.unshift(todo);
      }
      this.index = ++this.index % 3;
    };

    this.setState({
      list1: l1,
      list2: l2,
      list3: l3
    })
  }
  getList(list, index) {
    let i = 0;
    return list.reduce((li, todo) => {
      let j = i;
      li.push(
        <Todo data={todo} key={todo.time} finished={(id) => this.finished.bind(this)(id)}></Todo>
      )
      i++;
      return li;
    }, []);
  }
  finished(id) {
    this.local[id].finished = true;
    localStorage.setItem('todolist', JSON.stringify(this.local));
  }
  render() {
    let list1 = this.getList(this.state.list1, 0);
    let list2 = this.getList(this.state.list2, 1);
    let list3 = this.getList(this.state.list3, 2);

    return (      
      <div className="App">
      <section className="todolist">
        <section>{list1}</section>
        <section>{list2}</section>
        <section>{list3}</section>
      </section>
        <aside className="todoform">
          <form onSubmit={this.commit.bind(this)}>
            <input name="title" placeholder="请输入标题"></input>
            <textarea name="content" placeholder="请输入内容"></textarea>
            <button type="submit">新建</button>
          </form>
        </aside>
      </div>
    )
  }
 }
